package com.servo.service.impl;

import com.servo.mapper.CategoryMapper;
import com.servo.model.CategoryDO;
import com.servo.service.CategoryService;
import com.servo.utils.JsonData;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 分类表 服务实现类
 * </p>
 *
 * @author fwj
 * @since 2022-01-07
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;


    @Override
    public JsonData listWithTree() {
        List<CategoryDO> entities = categoryMapper.selectList(null);
        List<CategoryDO> level1Menus = entities.stream().filter(categoryDO -> categoryDO.getParentCid() == 0).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return JsonData.buildSuccess(level1Menus);
    }

    @Override
    public JsonData save(CategoryDO categoryDO) {
        categoryMapper.insert(categoryDO);
        return JsonData.buildSuccess();
    }

    @Override
    public JsonData update(CategoryDO categoryDO) {
        categoryMapper.updateById(categoryDO);
        return JsonData.buildSuccess();
    }

    @Override
    public JsonData getById(Long id) {
        CategoryDO categoryDO = categoryMapper.selectById(id);
        return JsonData.buildSuccess(categoryDO);
    }

    //递归查找所有菜单的子菜单
    private List<CategoryDO> getChildrens(CategoryDO root, List<CategoryDO> all) {

        List<CategoryDO> children = all.stream().filter(categoryDO -> {
            return categoryDO.getParentCid() == root.getId();
        }).map(categoryDO -> {
            //1、找到子菜单
            categoryDO.setChildren(getChildrens(categoryDO, all));
            return categoryDO;
        }).sorted((menu1, menu2) -> {
            //2、菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}